package io.github.iogogogo.middleware.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * Created by tao.zeng on 2024/12/10.
 */
@Slf4j
public class AesUtils {

    /**
     * 默认加密key
     */
    public final static String _DEFAULT_KEY = "ba60cb8f41c8b28e54e73ff19226da19";

    /**
     * 本例采用ECB加密模式，不需要设置偏移量
     */
    private final static int OFFSET = 0;

    /**
     * 加密模式
     */
    private final static String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    /**
     * 加密算法
     */
    private final static String ALGORITHM = "AES";


    /**
     * 加密
     *
     * @param key     加密密钥
     * @param content 需要加密的内容
     * @return 加密后的内容
     */
    public static String encrypt(String key, String content) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            // 加密
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * AES（256）解密
     *
     * @param key     解密密钥
     * @param content 待解密内容
     * @return 解密之后的内容
     */
    public static String decrypt(String key, String content) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            // 解密
            return new String(Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
